/*
 * @copyright: Huang Ding
 * @Author: ding-cx
 * @Date: 2021-01-08 11:05:22
 * @LastEditors: ding-cx
 * @LastEditTime: 2021-03-23 14:59:56
 * @Description: file content
 */

import {
  getCurrentInstance,
  inject,
  reactive,
  ref
} from "@vue/composition-api"

import useCrud from "@/hooks/crud"

import svs_sys_user_role from "@/service/sys/role"
import svs_sys_perm from "@/service/sys/permission"

let root;


export default {
  name: "",
  components: {

  },
  setup(props, ctx) {
    return useEnter(props, ctx)
  }
}

/**
 *组合api功能入口。组件中调用。
 *
 * @export
 * @param {*} props_
 * @param {*} ctx_
 * @return {*} 
 */
function useEnter(props_, ctx_) {

  const setups = {
    props: props_,
    ctx: ctx_,
    root: ctx_.root,
    that: getCurrentInstance(),
  }
  root = ctx_.root;

  const msg = inject('globalMessage')

  const options = {
    getConfig(page, condition) {

      const config = {
        url: svs_sys_user_role.api + "getSearchData",
        method: "post",
        data: {
          page: [page.size, page.offset]
        }
      }

      // console.log(config);

      return config;
    },
    reduceHeight: 290,
  }

  setups.that.$on("get-list", (msg) => {
    console.log(msg);
  })


  const beforeOpenDialog = (type, done) => {
    done()
  }


  let permRef = ref(null)
  /** dialog打开事件，其中可以拿到form的ref了。 */
  const onDialogOpen = (formRef, dialogState,row) => {
    // console.log(formRef);
    permRef.value = formRef.getRefs('perm_setting')
    if (dialogState === 0) {
      permRef.value.empty();//清空权限选中的状态。
    }else if(dialogState === 1){
      console.log(row);
      // 拿后台该角色的权限对象list赋值 给权限组件。
      svs_sys_perm.getAllPermByRoleId(row.id).then(res => {
        console.log(res);
        permRef.value.setCheckedList(res)
      })
    }
  }


  /** 增改表单选择权限触发的事件 */
  // const permDataList = ref({})
  // const checkGetDataList = (checkedData) => {
  //   console.log("get-check-data-event", checkedData);
  //   permDataList.value = checkedData;
  // }

  const cruds = useCrud(options)
  useCrudOption(cruds.option)
  const addSubmit = (data, loading, done) => {
    console.log(data);
    loading();
    // return;

    // console.log(permDataList.value);
    data.permission = permRef.value ? permRef.value.getDataList() : {};
    // console.log(data.permission);
    // return;
    svs_sys_user_role.post(data).then(data => {
      console.log(data);
      if (data.id > 0) {
        loading();
        msg.saveSuccess();
        cruds.refresh();
      }
    })

  }
  const rowEditSubmit = (data, loading, done) => {
    
    data.permission = permRef.value ? permRef.value.getDataList() : {};
    // console.log(data);
    svs_sys_user_role.put(data.id, data).then(data => {
      console.log(data);
      if (data.affectedRows >= 0) {
        loading();
        done();
        msg.editSuccess();
        cruds.refresh();
      }
    })
  }

  const rowDel = (scope) => {
    const {
      row
    } = scope;
    msg.confirm("确定要删除该角色吗？删除不可找回！").then(res => {
      svs_sys_user_role.delete(row.id).then(res => {
        if (res.affectedRows >= 0) {
          msg.deleteSuccess();
          cruds.refresh();
        }
      })
    }).catch(() => {})
  }
  // init get table data list
  cruds.refresh();

  const batchPerms = useBatchPerm(setups, cruds)

  return {
    ...cruds,
    addSubmit,
    rowEditSubmit,
    rowDel,
    ...batchPerms,

    beforeOpenDialog,
    onDialogOpen,
  }
}




/**
 *专门处理crud 组件的option配置。
 *
 * @param {*} option
 */
function useCrudOption(option) {
  option.table.column = [{
      label: "角色名",
      prop: "role_name",
      form: {
        componentProps: {
          placeholder: "角色名称",
        },
        rules: [{
          required: true,
          message: '请输入',
          trigger: 'blur'
        }]
      }
    },

    {
      label: "备注",
      prop: "memo"
    },

    {
      label: "创建人",
      prop: "create_user_real_name",
      form: {
        addDisplay: false,
        editDisplay: false,
      }
    },
    {
      label: "修改人",
      prop: "edit_user_real_name",
      form: {
        addDisplay: false,
        editDisplay: false,
      }
    },
    {
      label: "创建时间",
      prop: "createdAt",
      overflow: true,
      form: {
        addDisplay: false,
        editDisplay: false
      }
    },
    {
      label: "权限设置",
      prop: "perm_setting",
      hiden: true,
      form: {
        slot: false,
        span: 24,
        component: "PermissionSelectPannel",
        componentProps: {
          style: "margin:0;padding:8px;"
        }

      }
    }
  ]

  /** 搜索查询配置 */
  option.search.items = [{
    label: "查询",
    prop: "search",
    component: "el-input",
    componentProps: {
      placeholder: "请输入内容"
    },
  }]
}


/** 批量授权功能 */
function useBatchPerm(setups, cruds) {
  const visible = ref(false)
  const msg = inject('globalMessage')
  const openDialog = () => {
    if (cruds.selectedList.value.length < 1) {
      msg.emptyWarning();
      return;
    }
    visible.value = true;
  }

  /** dialog打开时事件，可拿到ref */
  const batchDialogOpen = () => {
    setups.root.$nextTick(() => {
      permissonSelectPannelRef.value.empty();
    })
  }

  // 选择授权的面板ref
  const permissonSelectPannelRef = ref(null)

  // dialog保存按钮
  const dialogSaveBtn = () => {
    // console.log(cruds.selectedList);
    const idList = cruds.selectedList.value.map(item => item.id)
    permissonSelectPannelRef.value.handleSave(idList);
  }

  return {
    dialogBatchPermVisible: visible,
    dialogBatchPermOpen: openDialog,
    permissonSelectPannelRef,
    dialogSaveBtn,
    batchDialogOpen,
  }
}
